package com.googlecode.keepwalking;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.util.Log;

public class WalkingTracker {
	private static final String TAG = "WalkigTracker";
	private static SimpleDateFormat fileformat = new SimpleDateFormat("yyyyMMdd");
	private static SimpleDateFormat logformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	private List<WalkingLog> logs;
	private Context context;
	
	public WalkingTracker(Context context) {
		logs = new ArrayList<WalkingLog>();
		this.context = context;
	}
	
	public synchronized void addLog(WalkingLog log) {
		logs.add(log);
	}
	public synchronized Object[] getLogs() {
		return logs.toArray();
	}
	
	public synchronized void persist() {
		if(logs.size() > 0) {
			Date filedate = new Date(logs.get(0).start);
			int day = filedate.getDate();
			StringBuilder builder = new StringBuilder();
			Iterator<WalkingLog> iter = logs.iterator();
			while(iter.hasNext()) {
				WalkingLog log = iter.next();
				if(day != new Date(log.start).getDate()) {
					writeToFile(fileformat.format(filedate) + ".log", builder);
					filedate = new Date(log.start);
					day = filedate.getDate();
					builder.setLength(0);
				}
				builder.append(logformat.format(new Date(log.start)) + "," 
						+ logformat.format(new Date(log.end)) + "\n");
			}
			writeToFile(fileformat.format(filedate) + ".log", builder);
		}
	}
	
	private void writeToFile(String name, StringBuilder sb) {
		try {
			FileOutputStream file = context.openFileOutput(name, Context.MODE_APPEND);
			file.write(sb.toString().getBytes());
			file.close();
		} catch(IOException e) {
			Log.d(TAG, "failed to write log to file: " + e);
		}
	}
}
